<template>
  <div>
    <div class="card-container">

      <el-card class="box-card" v-if="isHavePermission(['index:data:zhiMa'])"
        style="max-height: 900px; flex: 1; width: 300px; margin-right: 10px; overflow-y: auto;">
        <div slot="header" class="clearfix">
          <span>总收益</span>
          <div class="date-picker-container">
            <MobileDatePicker v-model="selectedDateRangeZhiMa" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              class="small-date-picker" @change="handleDateRangeChangeZhiMa" />
          </div>
          <div>
            <el-select v-model="channelCodeZhi" multiple clearable placeholder="请选择渠道编码" @change="handleChangePrice">
              <el-option v-for="(item, i) in extData.channelCodeAppList || []" :key="i" :label="item.key"
                         :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div>
          <ul>
            <li v-for="(item, index) in dataList" :key="index" class="data-item">
              <div class="data-info">
                <span class="data-name">{{ item.name }}：</span>
                <span class="data-number">{{ item.number || 0 }}</span>
              </div>
              <el-progress :percentage="parseFloat(calculatePercentage(item))" class="progress-bar"></el-progress>
            </li>
          </ul>
        </div>
      </el-card>


      <el-card class="box-card" v-if="isHavePermission(['index:data:money'])"
        style="max-height: 900px; flex: 1; width: 300px;margin-right: 10px; overflow-y: auto;">
        <div slot="header" class="clearfix">
          <span>商户消耗</span>
          <div class="date-picker-container">
            <MobileDatePicker v-model="selectedDateRangeApi" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              class="small-date-picker" @change="handleDateRangeChangeApi" />
          </div>
        </div>
        <div>
          <el-button @click="openIndexDialog" type="primary">更多信息</el-button>
          <ul>
            <li v-for="(item, index) in apiList" :key="index" class="data-item">
              <div class="data-info" style="display: flex;flex-direction: column;align-items: flex-start">
                <div style="display: flex">
                  <span class="data-name">{{ item.name }}：</span>
                  <span class="data-number amount-sum">{{ item.priceAmount || 0 }}</span>
                </div>
              </div>
              <el-progress :percentage="parseFloat(calculatePercentageApi(item))" class="progress-bar"></el-progress>
            </li>
          </ul>
        </div>
      </el-card>



      <el-card class="box-card" v-if="isHavePermission(['index:data:moneys'])"
        style="max-height: 900px; flex: 1; width: 300px;margin-right: 10px; overflow-y: auto;">
        <div slot="header" class="clearfix">
          <span>产品消耗</span>
          <div class="date-picker-container">
            <MobileDatePicker v-model="selectUnionAndProduct" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              class="small-date-picker" @change="handleUnionAndProduct" />
          </div>
        </div>
        <div>
          <el-button @click="openIndexUnionAndProductDialog" type="primary">更多信息</el-button>
          <ul>
            <li v-for="(item, index) in unionAndProductList" :key="index" class="data-item">
              <div class="data-info">
                <span class="data-name ">{{ item.name }}：</span>
                <span class="data-number amount-sum">{{ item.priceAmount || 0 }}</span>
                <!-- <span class="data-number amount-avg">{{ item.avgAmount || 0 }}</span> -->
              </div>
              <el-progress :percentage="parseFloat(calculatePercentageUnion(item))" class="progress-bar"></el-progress>
            </li>
          </ul>
        </div>
      </el-card>


      <el-card class="box-card" v-if="isHavePermission(['index:data:cost'])"
        style="max-height: 900px; flex: 1; width: 300px; overflow-y: auto;">
        <div slot="header" class="clearfix">
          <span>采量成本</span>
          <div class="date-picker-container">
            <MobileDatePicker v-model="selectedDateRangeCost" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              class="small-date-picker" @change="handleDateRangeChangeCost" />
            <div>
              <el-select v-model="channelCode" multiple clearable placeholder="请选择渠道编码" @change="handleChangeCost">
                <el-option v-for="(item, i) in extData.channelCodeAppList || []" :key="i" :label="item.key"
                           :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>


        </div>
        <div>
          <ul>
            <li v-for="(item, index) in cost" :key="index" class="data-item">
              <div class="data-info">
                <span class="data-name">{{ item.name }}：</span>
                <span class="data-number">{{ item.number || 0 }} | {{ item.cost || 0 }}￥</span>
              </div>
              <el-progress :percentage="parseFloat(calculatePercentageCost(item))" class="progress-bar"></el-progress>
            </li>
          </ul>
        </div>
      </el-card>
    </div>
    <div class="card-container" style="gap: 20px">
      <el-card class="box-card" v-if="isHavePermission(['index:data:user'])"
        style="max-height: 900px; flex: 1; width: 300px; overflow-y: auto;">
        <div slot="header" class="clearfix">
          <span>注册统计</span>
          <div class="date-picker-container" style="display: flex; gap: 20px;">
            <MobileDatePicker v-model="selectedDateRangeUser" type="datetimerange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']" format="yyyy-MM-dd HH:mm:ss" class="small-date-picker"
              @change="handleDateRangeChangeUser" />
            <div>
              <el-select v-model="regAppCode" @change="handleCodeRangeChangeUser" style="width: 100%;" clearable
                placeholder="请选择应用名称">
                <el-option v-for="(item, i) in extData.appInfoList || []" :key="i" :label="item.key"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div>
          <userInfoEcharts ref="userInfoEchartsRef"></userInfoEcharts>
        </div>
      </el-card>
      <el-card class="box-card" v-if="isHavePermission(['index:data:user'])"
        style="max-height: 900px; flex: 1; width: 300px; overflow-y: auto;">
        <div slot="header" class="clearfix">
          <span>最近七天注册统计</span>
          <div class="date-picker-container" style="display: flex; gap: 20px;">
            <MobileDatePicker v-model="selectedDateRangeUserSeven" type="daterange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              class="small-date-picker" @change="handleDateRangeChangeUserSeven" />
            <div>
              <el-select v-model="regAppCodeSevenDay" @change="handleCodeRangeChangeUserSeven" style="width: 100%;"
                clearable placeholder="请选择应用名称">
                <el-option v-for="(item, i) in extData.appInfoList || []" :key="i" :label="item.key"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div>
          <userInfoEcharts ref="userInfoEchartsSevenRef"></userInfoEcharts>
        </div>
      </el-card>
    </div>
    <div class="card-container" style="gap: 20px">
      <el-card class="box-card" v-if="isHavePermission(['index:data:user'])"
        style="max-height: 900px; flex: 1; width: 300px; overflow-y: auto;">
        <div slot="header" class="clearfix">
          <span>出单统计</span>
          <div class="date-picker-container" style="display: flex; gap: 20px;">
            <MobileDatePicker v-model="selectedDateRangeMerchantPush" type="datetimerange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']" format="yyyy-MM-dd HH:mm:ss" class="small-date-picker"
              @change="handleDateRangeChangeMerchantPush" />
          </div>
        </div>
        <div>
          <merchantPushEcharts ref="merchantPushEchartsRef"></merchantPushEcharts>
        </div>
      </el-card>
    </div>
    <div class="card-container" style="justify-content: flex-start; gap: 20px;">

      <el-card class="box-card" v-if="isHavePermission(['index:data:crmguanli'])">
        <div slot="header" class="clearfix">
          <span>CRM系统使用说明</span>
        </div>
        <div>
          <ul>
            <li>机构总账户登陆之后，需在【商户数据】-【成员管理】根据提示添加相应的员工信息</li>
            <li>在【商户数据】-【账户信息】可查看当前账户的余额和流水</li>
            <li>在【商户数据】-【任务列表】可查看当前任务</li>
            <li><span style="color: red;">员工账号是员工手机，密码默认为手机号后6位。员工账号密码可自行修改</span></li>
            <li>子账户推送状态打开才会有推送提醒，否则无推送提醒</li>
          </ul>
        </div>
      </el-card>

      <el-card class="box-card" v-if="isHavePermission(['index:data:apiguanli'])">
        <div slot="header" class="clearfix">
          <span>CRM系统使用说明</span>
        </div>
        <div>
          <ul>
            <li>在【商户数据】-【账户信息】可查看当前账户的余额和流水</li>
          </ul>
        </div>
      </el-card>
    </div>
    <indexDialog :title="`商户消耗统计 时间：${selectedDateRangeApi[0]} - ${selectedDateRangeApi[1]}`" ref="indexDialogRef">
    </indexDialog>
    <indexUnionAndProductDialog :title="`产品消耗统计 时间：${selectUnionAndProduct[0]} - ${selectUnionAndProduct[1]}`"
      ref="indexUnionAndProductDialogRef"></indexUnionAndProductDialog>
  </div>
</template>

<script>
import { listZhiMa, listApi, listBiaoDan, listCost, unionAndProductList, authAndSourceList, authAndSourceByWeekList, merchantPushByWeekList } from "@/api/index/index";
import { isHavePermission } from '@/directive/permission/hasPermi'
import dayjs from "dayjs";
import userInfoEcharts from "../components/indexCharts/userInfoEcharts.vue";
import merchantPushEcharts from "../components/indexCharts/merchantPushEcharts.vue";
import { baseInfoExtData } from "@/api/channel/baseInfo";
import indexDialog from './components/indexDialog'
import indexUnionAndProductDialog from './components/indexUnionAndProductDialog'
import { EventSourcePolyfill } from 'event-source-polyfill'
import { getToken } from "@/utils/auth";
export default {
  components: {
    userInfoEcharts,
    merchantPushEcharts,
    indexUnionAndProductDialog,
    indexDialog
  },
  data() {
    return {
      selectedDateRangeZhiMa: [`${dayjs().format('YYYY-MM-DD')}`, `${dayjs().format('YYYY-MM-DD')}`],
      selectedDateRangeApi: [`${dayjs().format('YYYY-MM-DD')}`, `${dayjs().format('YYYY-MM-DD')}`],
      selectedDateRangeCost: [`${dayjs().format('YYYY-MM-DD')}`, `${dayjs().format('YYYY-MM-DD')}`],
      selectUnionAndProduct: [`${dayjs().format('YYYY-MM-DD')}`, `${dayjs().format('YYYY-MM-DD')}`],
      selectedDateRangeUser: [
        dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        dayjs().startOf('hour').format('YYYY-MM-DD HH:mm:ss')
      ],
      selectedDateRangeUserSeven: [
        dayjs().subtract(6, 'day').startOf('day').format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD')
      ],
      selectedDateRangeMerchantPush: [
        dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        dayjs().startOf('hour').format('YYYY-MM-DD HH:mm:ss')
      ],
      dataList: [],     // 芝麻分数的数据
      apiList: [],      // 金额消耗的数据
      unionAndProductList: [],      // 联登和uv产品金额消耗的数据
      merchantPushList: [],
      cost: [],         // 表单成本的数据
      authAndSourceList: {},
      extData: [],
      regAppCode: "",
      regAppCodeSevenDay: "",
      regAppCodeMerchantPush: "",
      eventSource: null,
      messages: [],
      failMsg: [],
      channelCode: [],
      channelCodeZhi: []
    };
  },

  methods: {
    getOptions() {
      baseInfoExtData().then((response) => {
        this.extData = response.data;
      });
    },
    openIndexDialog() {
      this.$refs.indexDialogRef.open({
        totalConsumption: 0,
        averageValue: 0,
        totalCount: 0,
        productConsumptionDetails: this.apiList
      });
    },
    openIndexUnionAndProductDialog() {
      this.$refs.indexUnionAndProductDialogRef.open({
        totalConsumption: 0,
        averageValue: 0,
        totalCount: 0,
        productConsumptionDetails: this.unionAndProductList
      });
    },
    isHavePermission,
    // 芝麻分数 - 日期范围变化
    handleDateRangeChangeZhiMa(dateRange,channelCodeZhi) {
      if (!dateRange || dateRange.length !== 2) {
        this.$message.warning("请选择完整的日期范围");
        return;
      }
      const [startDate, endDate] = dateRange;
      this.fetchDataByDate('zhiMa', startDate, endDate,channelCodeZhi);
    },

    handleDateRangeChangeApi(dateRange) {
      if (!dateRange || dateRange.length !== 2) {
        this.$message.warning("请选择完整的日期范围");
        return;
      }
      const [startDate, endDate] = dateRange;
      this.fetchDataByDate('api', startDate, endDate);
    },

    handleUnionAndProduct(dateRange) {
      if (!dateRange || dateRange.length !== 2) {
        this.$message.warning("请选择完整的日期范围");
        return;
      }
      const [startDate, endDate] = dateRange;
      this.fetchDataByDate('unionAndProduct', startDate, endDate);
    },


    handleDateRangeChangeCost(dateRange,channelCode) {
      if (!dateRange || dateRange.length !== 2) {
        this.$message.warning("请选择完整的日期范围");
        return;
      }
      const [startDate, endDate] = dateRange;
      this.fetchDataByDate('cost', startDate, endDate,channelCode);
    },
    handleDateRangeChangeMerchantPush(dateRange) {
      if (!dateRange || dateRange.length !== 2) {
        this.$message.warning("请选择完整的日期范围");
        return;
      }
      const [startDate, endDate] = dateRange;
      this.fetchDataByDate('merchantPush', startDate, endDate);
    },
    handleDateRangeChangeUser(dateRange) {
      if (!dateRange || dateRange.length !== 2) {
        this.$message.warning("请选择完整的日期范围");
        return;
      }
      const [startDate, endDate] = dateRange;
      this.fetchDataByDate('user', startDate, endDate);
    },
    handleCodeRangeChangeUser(e) {
      console.log(e);
      this.regAppCode = e;
      this.fetchDataByDate('user', this.selectedDateRangeUser[0], this.selectedDateRangeUser[1]);
    },
    handleChangeCost(e) {
      let codeStr = ''
      if (e && e.length > 0) {
        codeStr = e.join(',');
      } else {
        this.channelCode = [];
      }
      this.fetchDataByDate('cost', this.selectedDateRangeCost[0], this.selectedDateRangeCost[1], codeStr);
    },
    handleChangePrice(e) {
      let codeStr = ''
      if (e && e.length > 0) {
        codeStr = e.join(',');
      } else {
        this.channelCodeZhi = [];
      }
      this.fetchDataByDate('zhiMa', this.selectedDateRangeCost[0], this.selectedDateRangeCost[1], codeStr);
    },
    handleCodeRangeChangeUserSeven(e) {
      this.regAppCodeSevenDay = e;
      this.getAuthAndSourceByWeekList()
    },
    handleDateRangeChangeUserSeven(dateRange) {
      if (!dateRange || dateRange.length !== 2) {
        this.$message.warning("请选择完整的日期范围");
        return;
      }
      this.selectedDateRangeUserSeven = dateRange
      this.getAuthAndSourceByWeekList()
    },
    async getAuthAndSourceByWeekList() {
      const res = await authAndSourceByWeekList({
        startDate: this.selectedDateRangeUserSeven[0],
        endDate: this.selectedDateRangeUserSeven[1],
        regAppCode: this.regAppCodeSevenDay
      })
      const data = res.data.authAndSourceList.reduce((pre, curr) => {
        pre.date.push(curr.time)
        pre.notAuthList.push(curr.notAuth)
        pre.authList.push(curr.auth)
        pre.allAuthList.push(curr.allAuth)
        return pre
      }, {
        date: [],
        notAuthList: [],
        authList: [],
        allAuthList: [],
      })
      this.$nextTick(() => {
        console.log(this.$refs.userInfoEchartsSevenRef)
        this.$refs.userInfoEchartsSevenRef.renderData(data)
      })
    },
    // 根据日期范围加载数据
    fetchDataByDate(type, startDate, endDate,channelCode) {
      let apiFunction;
      switch (type) {
        case 'zhiMa':
          apiFunction = listZhiMa;
          break;
        case 'api':
          apiFunction = listApi;
          break;
        case 'cost':
          apiFunction = listCost;
          break;
        case 'unionAndProduct':
          apiFunction = unionAndProductList;
          break;
        case 'user':
          apiFunction = authAndSourceList;
          break;
        case 'merchantPush':
          apiFunction = merchantPushByWeekList;
          break;
        default:
          return;
      }
      console.log(startDate, endDate)
      apiFunction({ startDate, endDate, regAppCode: type == 'user' ? this.regAppCode : null, channelCode: channelCode })
        .then((response) => {
          if (response.data) {
            switch (type) {
              case 'zhiMa':
                this.dataList = response.data.dataList || [];
                break;
              case 'api':
                this.apiList = response.data.apiList || [];
                break;
              case 'cost':
                this.cost = response.data.cost || [];
                break;
              case 'unionAndProduct':
                this.unionAndProductList = response.data.unionAndProductList || [];
                break;
              case 'merchantPush':
                this.merchantPushList = response.data.merchantPushList.reduce((pre, curr) => {
                  pre.date.push(curr.hourTime)
                  pre.successCountList.push(curr.successCount)
                  pre.waitPushCountList.push(curr.waitPushCount)
                  pre.totalCountList.push(curr.totalCount)
                  return pre
                }, {
                  date: [],
                  successCountList: [],
                  waitPushCountList: [],
                  totalCountList: [],
                })
                this.$nextTick(() => {
                  this.$refs.merchantPushEchartsRef.renderData(this.merchantPushList)
                })
                break;
              case 'user':
                this.authAndSourceList = response.data.authAndSourceList.reduce((pre, curr) => {
                  pre.date.push(curr.time)
                  pre.notAuthList.push(curr.notAuth)
                  pre.authList.push(curr.auth)
                  pre.allAuthList.push(curr.allAuth)
                  return pre
                }, {
                  date: [],
                  notAuthList: [],
                  authList: [],
                  allAuthList: [],
                })
                this.$nextTick(() => {
                  this.$refs.userInfoEchartsRef.renderData(this.authAndSourceList)
                })
                break;
            }
          } else {
            this.$message.error("未获取到数据");
          }
        })
        .catch((error) => {
          console.error('请求失败', error);
          this.$message.error("数据加载失败，请稍后重试");
        });
    },
    handleButtonClickZhiMa(index) {
      if (this.isHavePermission(['index:data:zhiMa'])) {
        this.selectedZhiMaIndex = index;
        this.handleType(index);
      }
    },
    handleButtonClickApi(index) {
      if (this.isHavePermission(['index:data:money'])) {
        this.selectedApiIndex = index;
        this.handleApiType(index);
      }
    },
    handleButtonClickbiaodan(index) {
      if (this.isHavePermission(['index:data:xiaohao'])) {
        this.selecteBiaoDanIndex = index;
        this.handlebiaodanType(index);
      }
    },
    handleButtonClickcost(index) {
      if (this.isHavePermission(['index:data:cost'])) {
        this.selecteCostIndex = index;
        this.handleCostType(index);
      }
    },
    handlebiaodanType(type) {
      listBiaoDan(type)
        .then((response) => {
          if (response.data && response.data.allData) {
            this.allData = response.data.allData;
          }
        })
        .catch((error) => {
          console.error('请求失败', error);
        });
    },
    handleType(type) {
      listZhiMa(type)
        .then((response) => {
          if (response.data && response.data.dataList) {
            this.dataList = response.data.dataList;
          }
        })
        .catch((error) => {
          console.error('请求失败', error);
        });
    },
    handleCostType(type) {
      listCost(type)
        .then((response) => {
          if (response.data && response.data.cost) {
            this.cost = response.data.cost;
          }
        })
        .catch((error) => {
          console.error('请求失败', error);
        });
    },
    handleApiType(type) {
      listApi(type)
        .then((response) => {
          if (response.data && response.data.apiList) {
            this.apiList = response.data.apiList;
          }
        })
        .catch((error) => {
          console.error('请求失败', error);
        });
    },
    calculatePercentage(item) {
      const total = this.dataList.find((data) => data.name === '总收益')?.number || 0;
      if (!total) return 0;
      return parseFloat(((item.number || 0) / total) * 100).toFixed(0);
    },
    calculatePercentageApi(item) {
      const totalItem = this.apiList.find((data) => data.name === '总消耗');
      const total = totalItem ? totalItem.priceAmount : 0;
      if (total === 0) return '0';
      return ((item.priceAmount || 0) / total * 100).toFixed(0);
    },

    calculatePercentageUnion(item) {
      const totalItem = this.unionAndProductList.find((data) => data.name === '总消耗');
      const total = totalItem ? totalItem.priceAmount : 0;
      if (total === 0) return '0';
      return ((item.priceAmount || 0) / total * 100).toFixed(0);
    },


    calculatePercentageCost(item) {
      const totalItem = this.cost.find((data) => data.name === '总数量|成本');
      const total = totalItem ? totalItem.cost : 0;
      if (total === 0) return '0';
      return ((item.cost || 0) / total * 100).toFixed(0);
    },


    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    buttonStyle(index, cardType) {
      let isSelected = false;
      switch (cardType) {
        case 'zhiMa':
          isSelected = this.selectedZhiMaIndex === index;
          break;
        case 'money':
          isSelected = this.selectedApiIndex === index;
          break;
        case 'biaodan':
          isSelected = this.selecteBiaoDanIndex === index;
          break;
        case 'cost':
          isSelected = this.selecteCostIndex === index;
          break;
        default:
          break;
      }

      return {
        backgroundColor: isSelected ? '#007bff' : 'transparent',
        color: isSelected ? '#fff' : '#000',
        padding: '6px 10px',
        fontSize: '13px',
        borderRadius: '4px',
        cursor: 'pointer',
      };
    },
    startSSE() {
      if(this.eventSource) return
      // SSE服务端地址（请替换为实际后端接口）
      const sseUrl = `${process.env.VUE_APP_BASE_API}/api/sse/connect`

      // 配置参数（支持自定义header）
      const options = {
        headers: {
          'Authorization': `Bearer ${getToken()}`, // 携带Token
          'Content-Type': 'text/event-stream'
        },
        heartbeatTimeout: 60000, // 心跳超时时间（毫秒）
        withCredentials: false // 跨域是否携带cookie（根据需求调整）
      }

      // 创建SSE连接
      this.eventSource = new EventSourcePolyfill(sseUrl, options)

      // 监听消息事件（默认事件名）
      this.eventSource.onmessage = (event) => {
        try {
          // 解析服务端发送的JSON数据（根据实际格式调整）
          const data = JSON.parse(event.data)
          this.messages.push(`收到消息：${JSON.stringify(data)}`)
          console.log(this.messages)
        } catch (e) {
          // 非JSON格式直接显示
          this.messages.push(`收到原始消息：${event.data}`)
        }
      }
      this.eventSource.addEventListener('MERCHANT_PUSH_FAILED', (e) => {
        const info = JSON.parse(e.data)
        this.failMsg.push(info)
        console.log(info)
        const notifyInstance = this.$notify({
          title: '推送失败',
          duration: 5000,
          message: this.$createElement('div', [
            // 原有的提示文本
            this.$createElement('div', { style: 'color: red' }, info.message),
            this.$createElement('div', { style: 'color: red' }, `用户id：${info.data.uid}`),
            // 新增的按钮
            this.$createElement('el-button', {
              style: 'margin-top: 10px;',
              props: {
                type: 'primary',
                size: 'mini'
              },
              on: {
                click: () => {
                  const infoId = info.data.pushInfoId;
                  const uid = info.data.uid;
                  notifyInstance.close();
                  this.$router.push({ path: `/merchant/pushInfo?infoId=${infoId}&uid=${uid}` });
                }
              }
            }, '前往查看') // 按钮文字
          ])
        });
      })
      // 连接成功事件
      this.eventSource.onopen = (event) => {
        console.log('SSE连接成功')
        console.log(event)
        this.isConnected = true
        this.messages.push('SSE连接已建立')
      }

      // 错误事件
      this.eventSource.onerror = (error) => {
        console.error('SSE错误:', error)
        this.messages.push(`连接错误：${error.message || '未知错误'}`)
        // 自动重连（根据需求调整）
        this.disconnectSSE()
      }
    },
    // 断开SSE连接
    disconnectSSE() {
      if (this.es) {
        this.eventSource.close() // 关闭连接
        this.eventSource = null
        this.messages.push('SSE连接已断开')
        console.log('SSE已断开')
      }
    }

  },
  mounted() {
    // 页面加载时，默认加载今天的日期范围数据
    const today = dayjs().format('YYYY-MM-DD');
    this.selectedDateRangeZhiMa = [today, today];
    this.selectedDateRangeApi = [today, today];
    this.selectedDateRangeCost = [today, today];
    this.selectUnionAndProduct = [today, today];
    this.getOptions();
    this.getAuthAndSourceByWeekList();
    // 加载当天的数据
    this.fetchDataByDate('zhiMa', today, today);
    this.fetchDataByDate('api', today, today);
    this.fetchDataByDate('cost', today, today);
    this.fetchDataByDate('unionAndProduct', today, today);
    this.fetchDataByDate('user', this.selectedDateRangeUser[0], this.selectedDateRangeUser[1]);
    this.fetchDataByDate('merchantPush', this.selectedDateRangeMerchantPush[0], this.selectedDateRangeMerchantPush[1]);
    this.startSSE();
  },

};
</script>


<style scoped>
/* 在手机上垂直展示 */
@media (max-width: 768px) {
  .card-container {
    display: block;
    margin: 20px 0;
    /* 移除水平边距 */
  }

  .box-card {
    max-width: 100%;
    min-width: 400px;
    /* 占满屏幕宽度 */
  }

  .button-container {
    justify-content: flex-start;
    /* 左对齐按钮 */
  }
}

/* 桌面上水平展示 */
@media (min-width: 769px) {
  .card-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    /* 卡片之间间隔相等 */
    margin: 20px 0 0;
    /* 顶部留出20px的间距 */
    padding: 0 40px;
    /* 左右边距为10px */
  }

  .button-container {
    justify-content: flex-end;
  }
}

.box-card {
  width: calc(30% - 20px);
  /* 每行最多三个卡片，并留出间距 */
  margin-bottom: 20px;
  /* 底部间距 */
}


.data-item {
  margin-bottom: 20px;
  font-size: 16px;
  color: #333;
}

.data-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  justify-content: space-between;
}

.data-name {
  font-weight: bold;
  margin-right: 10px;
}

.data-number {
  color: #007bff;
}

.progress-bar {
  width: 100%;
}

.data-number.amount-sum {
  margin-right: 35px;
}

.data-number.amount-avg {
  margin-right: 35px;
}
</style>
